/*
 * @Description: Stay hungry，Stay foolish
 * @Author: ''
 * @Date: 2023-09-18 16:36:16
 * @LastEditTime: 2023-09-19 08:58:38
 * @LastEditors: ''
 */
import {onBeforeUnmount,inject} from "vue"
import {on, off} from "../../../utils/dom"
// const ColorPickerInstance=inject('ColorPickerInstance')

export const useHas=(obj,handleChange,handleSlide,ColorPickerInstance,saturation=false)=>{
  const handleLeft=(e)=> {
    handleSlide(e, obj.left, 'left');
  }
  const handleRight= (e)=> {
    handleSlide(e, obj.right, 'right');
  }
  const handleUp =(e)=> {
    handleSlide(e, obj.up, 'up');
  }
  const handleDown= (e)=> {
    handleSlide(e, obj.down, 'down');
  }
  
  const handleMouseUp= ()=> {
    unbindEventListeners();
  }
  
  const handleMouseDown= (e)=> {
    ColorPickerInstance.handleOnDragging(true);
    // console.log('ColorPickerInstance',ColorPickerInstance)
    handleChange(e, true);
    // window.addEventListener('mousemove', this.handleChange, false);
    // window.addEventListener('mouseup', this.handleMouseUp, false);
    on(window, 'mousemove', handleChange);
    on(window, 'mouseup', handleMouseUp);

    if(saturation) on(window, 'mouseup', handleChange);
  }
  
  const unbindEventListeners= ()=> {
    // window.removeEventListener('mousemove', this.handleChange);
    // window.removeEventListener('mouseup', this.handleMouseUp);
    off(window, 'mousemove', handleChange);
    off(window, 'mouseup', handleMouseUp);
    // This timeout is required so that the click handler for click-outside
    // has the chance to run before the mouseup removes the dragging flag.
    if(saturation) off(window, 'mouseup', handleChange);
    setTimeout(() => ColorPickerInstance.handleOnDragging(false), 1);
  }
  
  const handleEscape=()=>{
    ColorPickerInstance.handleOnEscapeKeydown()
  }
  
  onBeforeUnmount(() => {
    unbindEventListeners();
  })

  return{
    handleLeft,
    handleRight,
    handleUp,
    handleDown,
    handleMouseDown,
    handleEscape
  }
}